package org.zdc.utils;
import haxe.Json;
using Lambda;

class Helper 
{
	/**
	 * 获取集成继承链的数组（如果有baseClass， 截至baseClass为止）
	 * @param	cls
	 * @param	?baseClass
	 * @return
	 */
	public static function getInheritClasses<T>(cls:Class<Dynamic>, ?baseClass:Class<T>):Array<Class<T>> {
		if (cls == null) {
			return null;
		}
		var clses:Array<Class<T>> = [];
		var c:Class<T> = untyped cls;
		while (c != null &&
			   (baseClass == null? true : (classIs(c, baseClass)))) { 
			clses.push(c);
			
			c = untyped Type.getSuperClass(c);
		}
		clses.reverse(); 	
		return clses;
	}
	
	/**
	 * 判断类一是否属于类二
	 * @param	cls1
	 * @param	cls2
	 * @return
	 */
	public static function classIs(cls1:Class<Dynamic>, cls2:Class<Dynamic>):Bool {
		if (cls1 == null && cls2 == null) {
			return false;
		}
		
		return (getInheritClasses(cls1).indexOf(cls2) > -1);		
	}
	
	/**
	 * 把相同类型的值从第二个复制到第一个, cpp会出现Internal的filed，不可用！
	 * @param	cls1
	 * @param	cls2
	 * @return
	 */
	//public static function joinTypedObjects<T>(hash1:T, hash2:T, ?overwrite:Bool = true):T {
		//if (hash2 == null || hash1 == null) {
			//return null;
		//}
		//Main.say("before:" + Json.stringify(hash1) + " " + Json.stringify(hash2));
		//var fs = Reflect.fields(hash2);	
		//var i:Int = 0;
		//for (f in fs) {		
			//if (Reflect.hasField(hash1, f) && !overwrite) {
				//continue;
			//}		
			//Reflect.setField(hash1, f, Reflect.field(hash2, f));
			//Main.say("process:" + Json.stringify(hash1) + " value:" + Reflect.field(hash2, f));
		//}
		//Main.say("after:" + Json.stringify(hash1));
		//return hash1;
	//}
	
	/**
	 * 把第二个散列的值复制到第一个
	 * @param	cls1
	 * @param	cls2
	 * @return
	 */
	public static function joinTwoHash<T>(hash1:Hash<T>, hash2:Hash<T>, ?overwrite:Bool = true):Hash<T> {
		if (hash2 == null || hash1 == null) {
			return null;
		}
		
		var fs = hash2.keys();	
		var i:Int = 0;
		for (f in fs) {		
			if (hash1.exists(f) && !overwrite) {
				continue;
			}		
			hash1.set(f, hash2.get(f));
		}
		return hash1;
	}
	
}